package com.ktty.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory factory = null;

    static {        //静态代码块，唯一一次创建SqlSessioninFactoy实例
        try{
            //SqlSessionFactoryBuilder只用一次（用完就销毁）
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            //读取 mybaits 核心配置文件
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            factory = builder.build(is);
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    //创建并返回SqlSession实例
    public static SqlSession createSqlSession(){
        return factory.openSession(false);   //关闭自动提交开启事务
    }

    //关闭sqlSession
    public static void closeSqlSession(SqlSession session){
        if(session != null){
            session.close();
        }
    }
}
